package com.jinwei.qunguanjia.web.user.controller;

import com.jinwei.qunguanjia.common.core.domain.Response;
import com.jinwei.qunguanjia.common.utils.SystemContextUtils;
import com.jinwei.qunguanjia.user.dto.UserIntegralDTO;
import com.jinwei.qunguanjia.user.dto.UserDTO;
import com.jinwei.qunguanjia.user.dto.UserGroupUnlockDTO;
import com.jinwei.qunguanjia.user.service.UserGroupUnlockService;
import com.jinwei.qunguanjia.user.service.UserIntegralService;
import com.jinwei.qunguanjia.user.service.UserService;
import com.jinwei.qunguanjia.web.user.vo.UserGroupUnlockVO;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 解锁群相关接口
 *
 * @author yuanzs
 */
@RestController
@RequestMapping("/userGroupUnlock")
public class UserGroupUnlockController {

    @Resource
    private UserGroupUnlockService userGroupUnlockService;

    @Resource
    private UserIntegralService userIntegralService;

    @Resource
    private UserService userService;

    /**
     * 解锁群
     * @param userGroupUnlockVO 对象
     */
    @PostMapping("/save")
    public Response save(@Validated @RequestBody UserGroupUnlockVO userGroupUnlockVO) throws IllegalAccessException {
        String userId = SystemContextUtils.getUserId();
        UserGroupUnlockDTO userGroupUnlockQueryDTO = new UserGroupUnlockDTO();
        userGroupUnlockQueryDTO.setGroupId(userGroupUnlockVO.getGroupId());
        userGroupUnlockQueryDTO.setUserId(userId);
        userGroupUnlockQueryDTO = userGroupUnlockService.get(userGroupUnlockQueryDTO);
        if (null == userGroupUnlockQueryDTO) {
            UserDTO userQueryDTO = userService.get(userId);
            if (Integer.parseInt(userQueryDTO.getMyIntegral()) - 10 < 0) {
                return Response.fail("积分不足");
            }
            UserGroupUnlockDTO userGroupUnlockDTO = new UserGroupUnlockDTO();
            BeanUtils.copyProperties(userGroupUnlockVO, userGroupUnlockDTO);
            userGroupUnlockDTO.setUserId(SystemContextUtils.getUserId());
            userGroupUnlockService.save(userGroupUnlockDTO);
            UserIntegralDTO integralDTO = UserIntegralDTO.builder()
                    .integralType("1")
                    .integralSource("5")
                    .integralNumber("10")
                    .userId(userId)
                    .build();
            userIntegralService.save(integralDTO);
            int myIntegral = Integer.parseInt(userQueryDTO.getMyIntegral());
            myIntegral = myIntegral - 10;
            UserDTO userDTO = new UserDTO();
            userDTO.setUserId(userId);
            userDTO.setMyIntegral(String.valueOf(myIntegral));
            userService.update(userDTO);
        }
        return Response.success();
    }
    
}
